package com.example.scala.chapter2


import java.io.{BufferedReader, BufferedWriter, InputStream, InputStreamReader, OutputStream, OutputStreamWriter}
import java.lang.Thread.sleep
import java.net.{ServerSocket, Socket}
import java.nio.charset.StandardCharsets


/**
 *
 * Description:
 *
 * Create by lucienoz on 2021/10/13.
 * Copyright © 2021 lucienoz. All rights reserved.
 */
object chapter07 {
  def main(args : Array[String]) : Unit = {
    val serverSocket = new ServerSocket ( 9999 )
    val client : Socket = serverSocket.accept () //此方法为阻塞方法
    println(client.getLocalSocketAddress+" is connectting")
    //通过输入流进行包装
    val clientInputStream : InputStream = client.getInputStream
    val reader = new BufferedReader ( new InputStreamReader ( clientInputStream, StandardCharsets.UTF_8 ) )
    val clientoutputStream : OutputStream = client.getOutputStream
    val bufferedWriter = new BufferedWriter ( new OutputStreamWriter ( clientoutputStream, StandardCharsets.UTF_8 ) )

    bufferedWriter.write("Server"+client.getLocalSocketAddress+"\n")
    bufferedWriter.flush()
    client.shutdownOutput()

    var flag : Boolean = true
    while(flag) {

      val charArr : Array[Char] = new Array[Char]( 1024 )
      val i : Int = reader.read ( charArr ) //调用此方法时应确保，对面的输出流没有关闭否则报错

      if(i == -1) {
        flag = false
      }else{
        charArr.foreach(char => if(char != 0) print(char))

      }
    }
    println("===========>>")
    client.shutdownInput()

    Thread.sleep(5000)

    client.close()












  }

}
